//随机乱斗匹配模块
class RandomMatching{
    constructor(docker){
        this.docker=docker;
        this.orders=[]; //存放当前正在匹配中的玩家_id
    }
    joinOrder(user){
        let index=this.orders.indexOf(user._id);
        if(index<0){
            this.orders.push(user._id);
            //如果满2人，则直接创建房间，开始游戏
            this.sendOrdersUsers();
            if(this.orders.length===2){
                let Room=require('./Room');
                let room=new Room({roomId:this.docker.currentRoomId},this.docker);
                this.docker.rooms[room.roomId]=room;
                this.docker.currentRoomId++;
                //从匹配队列中移除用户将用户加入房间
                for(let i=0;i<this.docker.roomUserCount;i++){
                    let user=this.docker.users[this.orders.shift()];
                    user.group=i;
                    room.addUser(user);
                }
                //给房间内用户派发游戏开始的消息
                room.gameStart();
            }
        }
    }
    sendOrdersUsers(){
        let obj={e:'userMatching',users:[]};
        for(let i=0;i<this.orders.length;i++){
            obj.users.push(this.docker.users[this.orders[i]].getMessage());
        }
        for(let i=0;i<this.orders.length;i++){
            this.docker.users[this.orders[i]].send(obj);
        }
    }
}

module.exports=RandomMatching;